package com.iotechn.unimall.admin.api.goods;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.google.gson.Gson;
import com.iotechn.unimall.core.exception.AdminServiceException;
import com.iotechn.unimall.core.exception.ExceptionDefinition;
import com.iotechn.unimall.core.exception.ServiceException;
import com.iotechn.unimall.data.domain.*;
import com.iotechn.unimall.data.dto.BiaozhunCountDTO;
import com.iotechn.unimall.data.dto.goods.YanshouDTO;
import com.iotechn.unimall.data.enums.BizType;
import com.iotechn.unimall.data.mapper.*;
import com.iotechn.unimall.data.model.Page;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by rize on 2019/7/11.
 */
@Service
public class AdminYanshouServiceImpl implements AdminYanshouService {


    @Autowired
    private ShopYanshouMapper spuMapper;
    @Autowired
    private ShopBiaozhunLogMapper  shopBiaozhunLogMapper;

    @Autowired
    private ImgMapper imgMapper;
    @Autowired
    private ShopBiaozhunMapper shopBiaozhunMapper;

    @Autowired
    private UserShopMapper shopMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String create(YanshouDTO spuDTO, Long adminId) throws ServiceException {

        Date now = new Date();
        ShopYanshouDO LogDO = new ShopYanshouDO();
        BeanUtils.copyProperties(spuDTO, LogDO);
        LogDO.setGmtUpdate(now);
        LogDO.setGmtCreate(now);
        LogDO.setAdminId(adminId);
        LogDO.setGmt_day(now);
        Gson gson=new Gson();
        LogDO.setFile(gson.toJson(spuDTO.getFile()));
        if(spuDTO.getImgList()!=null && spuDTO.getImgList().size()>0){
            String imgs = String.join(",",spuDTO.getImgList());
            LogDO.setImg(imgs);
        }
        LogDO.setStatus(0);

        if(spuMapper.insert(LogDO)>0){
            spuDTO.setId(LogDO.getId());
            /*List<ShopBiaozhunYanshouDO> biaozhunList=spuDTO.getBiaozhunList();
            if(biaozhunList!=null && biaozhunList.size()>0){
                for(ShopBiaozhunYanshouDO s:biaozhunList){
                    s.setAdminId(adminId);
                    s.setGmt_day(now);
                    s.setShop_log_id(LogDO.getId());
                    s.setType(LogDO.getType());
                }
                shopBiaozhunYanshouMapper.batchInsert(biaozhunList);
            }*/
           }
    //插入IMG
        insertSpuImg(spuDTO, LogDO.getId(), now);



         return "ok";
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String edit(YanshouDTO spuDTO, Long adminId) throws ServiceException {
        if (spuDTO.getId() == null) {
            throw new AdminServiceException(ExceptionDefinition.PARAM_CHECK_FAILED);
        }

        Date now = new Date();
        ShopYanshouDO logDO = new ShopYanshouDO();
        BeanUtils.copyProperties(spuDTO, logDO);
        Gson gson=new Gson();
        logDO.setFile(gson.toJson(spuDTO.getFileList()));
        if(spuDTO.getImgList()!=null && spuDTO.getImgList().size()>0){
            String imgs = String.join(",",spuDTO.getImgList());
            logDO.setImg(imgs);
        }
        logDO.setGmtUpdate(now);
        if(spuMapper.updateById(logDO)>0){
           /* shopBiaozhunYanshouMapper.batchDelete(logDO.getId());
            List<ShopBiaozhunLogDO> biaozhunList=spuDTO.getBiaozhunList();
            if(biaozhunList!=null) {

                for (ShopBiaozhunLogDO s : biaozhunList) {
                    s.setAdminId(adminId);
                    s.setGmt_day(now);
                    s.setType(logDO.getType());
                    s.setShop_log_id(logDO.getId());
                }
                shopBiaozhunYanshouMapper.batchInsert(biaozhunList);
            }*/
        }

        imgMapper.delete(new EntityWrapper<ImgDO>().eq("biz_id", logDO.getId()).eq("biz_type", BizType.LOG.getCode()));
        //插入IMG
        insertSpuImg(spuDTO, logDO.getId(), now);
        return "ok";
    }



    private void insertSpuImg(YanshouDTO spuDTO, Long bizId, Date now) {
        List<String> imgList = spuDTO.getImgList();
        if(imgList!=null && imgList.size()>0){
            List<ImgDO> imgDOList = imgList.stream().map(item -> {
                ImgDO imgDO = new ImgDO();
                imgDO.setBizType(BizType.GOODS.getCode());
                imgDO.setBizId(bizId);
                imgDO.setUrl(item);
                imgDO.setGmtCreate(now);
                imgDO.setGmtUpdate(now);
                return imgDO;
            }).collect(Collectors.toList());
            imgMapper.insertImgs(imgDOList);
        }

    }

    @Override
    public Page<YanshouDTO> list(Long shopId, String shopName,Integer type, Integer page, Integer limit, Long adminId) throws ServiceException {
        List<YanshouDTO> LogDOS = spuMapper.getSpuDTOList(shopId, shopName, null,(page - 1) * limit, limit);
        Integer count = spuMapper.getSpuDTOListCount(shopId, shopName,null);
        Page<YanshouDTO> dtoPage = new Page<>(LogDOS, page, limit, count);

        return dtoPage;
    }

    @Override
    public YanshouDTO detail(Long spuId, Long adminId) throws ServiceException {

        ShopYanshouDO logDO=spuMapper.selectById(spuId);
        YanshouDTO spuDTO = new YanshouDTO();
        BeanUtils.copyProperties(logDO, spuDTO);
        spuDTO.setFileList(spuDTO.getFile());
        Wrapper<ShopBiaozhunLogDO> wrapper = new EntityWrapper<ShopBiaozhunLogDO>();
        wrapper.eq("shop_log_id",spuId);
        /*List<ShopBiaozhunYanshouDO> ShopBiaozhunLogDOS = shopBiaozhunYanshouMapper.selectList(wrapper);
        spuDTO.setBiaozhunList(ShopBiaozhunLogDOS);**/
        if(logDO.getImg()!=null && !logDO.getImg().equals("")){
            String[] arr = logDO.getImg().split(",");
            List<String> list = Arrays.asList(arr);
            spuDTO.setImgList(list);
        }

        return spuDTO;
    }

    @Override
    public YanshouDTO logDetail(Long shopId, Integer type, String gmtDay, Long adminId) throws ServiceException {
        EntityWrapper<ShopYanshouDO> wrapper= new EntityWrapper<ShopYanshouDO>();
        if(gmtDay==null){
            Date nowDate=new Date();
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            gmtDay=df.format(nowDate);
        }
        wrapper.eq("shop_id", shopId).eq("type",type).eq("gmt_day",gmtDay).orderDesc(Arrays.asList(new String[] {"id"}));
        List<ShopYanshouDO> list=spuMapper.selectList(wrapper);
        ShopYanshouDO logDO=null;
        YanshouDTO spuDTO = new YanshouDTO();

        if(list!=null && list.size()>0){
            logDO=list.get(0);
            BeanUtils.copyProperties(logDO, spuDTO);
            spuDTO.setFileList(spuDTO.getFile());
        /*    Wrapper<ShopBiaozhunLogDO> wrapperBiaozhun = new EntityWrapper<ShopBiaozhunLogDO>();
            wrapperBiaozhun.eq("shop_log_id",logDO.getId());
            List<ShopBiaozhunLogDO> ShopBiaozhunLogDOS = shopBiaozhunLogMapper.selectList(wrapperBiaozhun);
            spuDTO.setBiaozhunList(ShopBiaozhunLogDOS);
          */  if(logDO.getImg()!=null && !logDO.getImg().equals("")){
                String[] arr = logDO.getImg().split(",");
                List<String> listImg = Arrays.asList(arr);
                spuDTO.setImgList(listImg);
            }

        }

        return spuDTO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String delete(Long spuId, Long adminId) throws ServiceException {
        if (spuMapper.deleteById(spuId) <= 0) {
            throw new AdminServiceException(ExceptionDefinition.GOODS_NOT_EXIST);
        }
        imgMapper.delete(new EntityWrapper<ImgDO>().eq("biz_id", spuId).eq("biz_type", BizType.GOODS.getCode()));
        return "ok";
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String batchDelete(String idsJson, Long adminId) throws ServiceException {
        List<Long> ids = JSONObject.parseArray(idsJson, Long.class);
        if (CollectionUtils.isEmpty(ids)) {
            throw new AdminServiceException(ExceptionDefinition.GOODS_NOT_EXIST);
        }
        if (spuMapper.delete(new EntityWrapper<ShopYanshouDO>().in("id", ids)) <= 0) {
            throw new AdminServiceException(ExceptionDefinition.GOODS_NOT_EXIST);
        }
        imgMapper.delete(new EntityWrapper<ImgDO>().in("biz_id", ids).eq("biz_type", BizType.GOODS.getCode()));

        return "ok";
    }




    @Override
    @Transactional(rollbackFor = Exception.class)
    public YanshouDTO freezeOrActivation(Long spuId, Integer status, Long adminId) throws ServiceException {
        ShopYanshouDO LogDO = spuMapper.selectById(spuId);

        if (LogDO == null) {
            throw new AdminServiceException(ExceptionDefinition.GOODS_NOT_EXIST);
        }

        LogDO.setStatus(status);
        LogDO.setGmtUpdate(new Date());
        if (spuMapper.updateById(LogDO) <= 0) {
            throw new AdminServiceException(ExceptionDefinition.GOODS_UPDATE_SQL_FAILED);
        }

        YanshouDTO spuDTO = new YanshouDTO();
        BeanUtils.copyProperties(LogDO, spuDTO);

         return spuDTO;
    }
}
 